package com.amphiprion.prototype.component;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

import com.amphiprion.prototype.ScreenProperty;
import com.amphiprion.prototype.util.BitmapUtil;
import com.amphiprion.prototype.util.NormalizedBitmap;

public class ImageComponent extends GameComponent {
	protected String imageUri;
	public NormalizedBitmap bitmap;
	protected Paint paint;

	public ImageComponent(String imageUri, float x, float y) {
		this(imageUri, x, y, 255);
	}

	public ImageComponent(String imageUri, float x, float y, int alpha) {
		this.imageUri = imageUri;
		this.x = x;
		this.y = y;
		this.alpha = alpha;
		paint = new Paint();
		paint.setAntiAlias(true);
	}

	public boolean isInside(float px, float py) {
		if (bitmap == null || bitmap.bitmap == null) {
			return false;
		}
		if (px >= x - bitmap.bitmap.getWidth() * bitmap.normalizedScale / 2 && px <= x + bitmap.bitmap.getWidth() * bitmap.normalizedScale / 2) {
			if (py >= y - bitmap.bitmap.getHeight() * bitmap.normalizedScale / 2 && py <= y + bitmap.bitmap.getHeight() * bitmap.normalizedScale / 2) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void activate() {
		bitmap = BitmapUtil.loadBitmap(imageUri);
	}

	@Override
	public void desactivate() {
		BitmapUtil.unloadBitmap(imageUri);
		bitmap = null;
	}

	@Override
	public void onDraw(Canvas canvas, ScreenProperty screenProperty) {
		// if (bitmap.normalizedScale!=1) {
		// Log.d(ApplicationConstants.PACKAGE,
		// "scale="+scale*bitmap.normalizedScale +
		// "  total="+scale*bitmap.normalizedScale*screenProperty.screenScale);
		// }
		if (bitmap != null && bitmap.bitmap != null) {
			drawImage(canvas, bitmap.bitmap, x, y, scale * bitmap.normalizedScale, screenProperty);
		}
	}

	protected void drawImage(Canvas canvas, Bitmap img, float centerX, float centerY, float scale, ScreenProperty screenProperty) {
		if (alpha == 0 || img == null) {
			return;
		}
		paint.setAlpha(alpha);
		Matrix m = new Matrix();
		m.postTranslate(-img.getWidth() / 2, -img.getHeight() / 2);
		m.postRotate(screenProperty.screenRotation + rotation);
		m.postScale(scale * screenProperty.screenScale, scale * screenProperty.screenScale);

		if (screenProperty.screenRotation == 0) {
			m.postTranslate(centerX * screenProperty.screenScale + screenProperty.screenOffsetX, centerY * screenProperty.screenScale + screenProperty.screenOffsetY);
		} else {
			m.postTranslate(canvas.getWidth() - centerY * screenProperty.screenScale + screenProperty.screenOffsetX, centerX * screenProperty.screenScale
					+ screenProperty.screenOffsetY);
		}
		canvas.drawBitmap(img, m, paint);
	}

}
